#include"Heap.h"

void HPInit(Heap* php) {
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}
void Swap(DataType* a, DataType* b) {
	DataType tmp = *a;
	*a = *b;
	*b = tmp;
}
void AdJustUp(int* arr, int child) {
	int parent = (child - 1) / 2;
	while (child) {
		if (arr[child] < arr[parent]) {
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else break;
	}
}

void HPPush(Heap* php, DataType x) {
	assert(php);
	if (php->capacity == php->size) {
		int newCapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		DataType* tmp = (DataType*)realloc(php->arr, sizeof(DataType)*newCapacity);
		if (tmp == NULL) {
			perror("realloc fail");
			exit(1);
		}
		php->arr = tmp;
		php->capacity = newCapacity;
	}
	php->arr[php->size++] = x;
	AdJustUp(php->arr, php->size - 1);
}
void AdJustDown(int* arr, int parent,int size) {
	int child = parent * 2 + 1;
	while (child < size) {
		if (child + 1 < size && arr[child] > arr[child + 1]) { 
			child++;
		}
		if (arr[child] < arr[parent]) {
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else break;
	}
}

void HPPop(Heap* php) {
	assert(php && php->size);
	Swap(&php->arr[0], &php->arr[php->size - 1]);
	php->size--;
	AdJustDown(php->arr, 0, php->size);
}
DataType HPTop(Heap* php) {
	assert(php && php->size);
	return php->arr[0];
}
bool HPEmpty(Heap* php) {
	return php->size == 0;
}
void HPDestroy(Heap* php) {
	assert(php);
	if (php->arr) free(php->arr);
	php->arr = NULL;
	php->capacity = php->size = 0;
}